package com.echo.im.domain.group.manager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.echo.im.common.exception.GlobalException;
import com.echo.im.common.result.ResultEnum;

import com.echo.im.domain.group.dto.GroupDTO;
import com.echo.im.infrastructure.session.SessionContext;
import com.echo.im.infrastructure.session.UserSession;
import com.echo.im.repository.dao.entity.Group;
import com.echo.im.repository.dao.entity.GroupMember;
import com.echo.im.repository.dao.entity.User;
import com.echo.im.repository.dao.mapper.GroupMapper;
import com.echo.im.repository.dao.mapper.GroupMemberMapper;
import com.echo.im.repository.dao.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: echo
 * @time: 2024-08-17
 */
@Component
@RequiredArgsConstructor
public class GroupManager {

    private final GroupMapper groupMapper;
    private final GroupMemberMapper groupMemberMapper;
    private final UserMapper userMapper;

    public Group getAndCheckByGroupId(Long groupId) {
        Group group = groupMapper.selectById(groupId);
        if (Objects.isNull(group)||group.getDeleted()||group.getIsBanned()) {
            throw new GlobalException(ResultEnum.NOT_EXIST);
        }
        return group;
    }

    public void createGroup(GroupDTO dto) {
        //查询当前用户信息
        UserSession session = SessionContext.getSession();
        User user = userMapper.selectById(session.getUserId());

        // 保存群组数据
        Group group = BeanUtil.copyProperties(dto, Group.class);
        group.setOwnerId(user.getId());
        groupMapper.insert(group);

        // 把群主加入群
        GroupMember member = new GroupMember();
        member.setGroupId(group.getId());
        member.setUserId(user.getId());
        member.setHeadImage(user.getHeadImageThumb());
        member.setRemarkNickName(dto.getRemarkNickName());
        member.setRemarkGroupName(dto.getRemarkGroupName());
        groupMemberMapper.insert(member);

        dto.setId(dto.getId());
        dto.setShowNickName(StrUtil.isEmpty(dto.getRemarkNickName()) ? member.getUserNickName() : dto.getRemarkNickName());
        dto.setShowGroupName(StrUtil.isEmpty(dto.getRemarkGroupName()) ? group.getName() : dto.getRemarkGroupName());

    }

    public Group checkGroupOwner(Long ownerId, Long groupId) {
        Group group = this.getAndCheckByGroupId(groupId);
        if (group!=null&&!group.getOwnerId().equals(ownerId)) {
            throw new GlobalException(ResultEnum.NO_PERMISSION);
        }
        return group;
    }

    public void deleteGroup(Long groupId) {

        // 逻辑删除群数据
        groupMapper.deleteById(groupId);

        // 删除成员数据
        groupMemberMapper.deleteByGroupId(groupId);
    }
}
